package com.julyup.face.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;

/**
 *
 * 人脸比对API
 *
 * @Author: zhenzhong.wang@honeywell.com
 * @Date: 2019/3/22 10:33 AM
 */
public class FaceCompareUtils {

  private static final RequestConfig defaultConfig;
  static {
    defaultConfig = RequestConfig.custom().
        setSocketTimeout(10000).
        setConnectTimeout(10000).
        setConnectionRequestTimeout(10000).
        build();
  }

  public static Double compare(String fileUrl1, String fileUrl2) throws IOException {
    HttpPost httpPost = new HttpPost("https://api-cn.faceplusplus.com/facepp/v3/compare");

    HttpEntity requestEntity = MultipartEntityBuilder.create()
        .addTextBody("api_key", "zc5Iwp9FzaL0AtnAXd4CwC4ZM-T0GFAD")
        .addTextBody("api_secret", "IQx8kTWdIRUB5lKkISvCf-3QDcAgJJ5E")
        .addBinaryBody("image_file1", new File(fileUrl1))
        .addBinaryBody("image_file2", new File(fileUrl2))
        .build();

    httpPost.setEntity(requestEntity);
    httpPost.setConfig(defaultConfig);

    CloseableHttpResponse response = null;
    try {
      response = HttpClients.createDefault().execute(httpPost);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
    HttpEntity responseEntity = response.getEntity();
    if (responseEntity != null) {
      JSONObject obj = JSON.parseObject(EntityUtils.toString(responseEntity));
      return Double.valueOf(obj.get("confidence").toString());
    } else {
      return null;
    }
  }
}
